<!--
 * @Descripttion: 
 * @version: 
 * @Author: cyj
 * @Date: 2022-12-31 14:32:36
-->
<template>
    <div class="login-pop">
        <!-- 关闭按钮 -->
        <div class="close" @click="closeLogin">
            <el-icon size="23">
                <CloseBold />
            </el-icon>
        </div>

        <!-- 手机号登录 -->
        <div class="phone-login" v-if="loginWay === 0">
            <h2>手机号登录</h2>
            <div class="imgs">
                <span class="iconfont icon-shouji"></span>
            </div>
            <!-- 手机号、密码登录表单 -->
            <div class="login-form">
                <el-form label-width="70px">
                    <el-form-item label="手机号">
                        <el-input v-model="phoneNum" placeholder="请输入手机号" />
                    </el-form-item>
                    <el-form-item label="密码">
                        <el-input type="password" v-model="password" placeholder="请输入登录密码" />
                    </el-form-item>
                    <el-form-item>
                        <div class="ToCaptcha" @click="changeLoginWay(2)">验证码登录</div>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="danger" @click="phoneLogin(1)">登录</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="changeLoginWay(3)">注册</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="other-way" @click="changeLoginWay(1)">
                <span><i class="iconfont icon-erweima"></i> <i>扫码登录</i></span>
            </div>
        </div>

        <!-- 扫码登录 -->
        <div class="qr-login" v-if="loginWay === 1">
            <div class="qr">
                <h2>扫码登录</h2>
                <img :src="qrUrl" alt="">
                <p class="failqr" v-if="failqr">二维码已失效,<span @click="qrLogin">点击刷新</span></p>
                <p class="text" v-if="!scanQr">使用<span style="color: #5091ca">网易云音乐手机APP</span>扫码登录</p>
                <p class="text" v-if="scanQr">扫描成功,请在手机上确认</p>

                <!-- 其他登录方式 -->
                <div class="other-way" @click="changeLoginWay(0)" style="margin-top: 30px">
                    <span>
                        <i class="iconfont icon-shouji e"></i>
                        <i class="text"> 手机号登录</i>
                    </span>
                </div>
                <div class="other-way" style="padding-top: 50px" @click="changeLoginWay(3)">
                    <span>还没有账号,去注册</span>
                </div>
            </div>
        </div>

        <!-- 验证码登录 -->
        <div class="captcha-login" v-if="loginWay === 2">
            <h2>手机号验证码登录</h2>
            <div class="imgs">
                <span class="iconfont icon-shouji"></span>
            </div>
            <div class="login-form">
                <el-form label-width="70px">
                    <el-form-item label="手机号">
                        <el-input v-model="phoneNum" placeholder="请输入手机号" />
                    </el-form-item>
                    <el-form-item label="验证码" class="captcha-input">
                        <el-input v-model="phoneCap" placeholder="请输入验证码" />
                        <div class="captcha-btn" v-if="!isGetCaptcha" @click="getCaptcha">获取验证码</div>
                        <div class="captcha" v-else>{{ tip }}</div>
                    </el-form-item>
                    <el-form-item>
                        <div class="ToCaptcha" @click="changeLoginWay(0)">密码登录</div>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="danger" @click="phoneLogin(2)">登录</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="changeLoginWay(3)">注册</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="other-way" @click="changeLoginWay(1)">
                <span><i class="iconfont icon-erweima"></i> <i>扫码登录</i></span>
            </div>
        </div>

        <!-- 注册新用户 -->
        <div class="register" v-if="loginWay === 3">
            <h2>注册新用户</h2>
            <!-- 注册用户表单 -->
            <div class="reg-form">
                <el-form :model="ruleForm" label-width="80px" label-position="right" :rules="rules" ref="ruleForms">
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="ruleForm.phone" placeholder="请输入手机号" />
                    </el-form-item>
                    <el-form-item label="密码" prop="pass">
                        <el-input type="password" v-model="ruleForm.pass" placeholder="密码为8~20位,必须包含字母数字" />
                    </el-form-item>
                    <el-form-item label="确认密码" prop="checkPass">
                        <el-input type="password" v-model="ruleForm.checkPass" placeholder="请确认密码" />
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname">
                        <el-input v-model="ruleForm.nickname" placeholder="请输入昵称" />
                    </el-form-item>
                    <el-form-item label="验证码" prop="captcha" class="captcha-input">
                        <el-input v-model="ruleForm.captcha" placeholder="请输入验证码" />
                        <div class="captcha-btn" v-if="!isGetCaptcha" @click="getCaptcha">获取验证码</div>
                        <div class="captcha" v-else>{{ tip }}</div>
                    </el-form-item>
                </el-form>
            </div>
            <div class="reg-btns">
                <div class="reg-btn">
                    <el-button type="primary" @click="registerUser">注册</el-button>
                </div>
                <div class="reg-btn">
                    <el-button @click="changeLoginWay(0)">返回登录</el-button>
                </div>
            </div>
        </div>

    </div>
</template>

<script setup>
import { getQrKey, getLoginQr, checkLoginQr, getUserAccount, sendCaptcha, loginByPhoneAndPwdOrCta, checkCaptcha, register, loginStatus } from '@/api/login/login.js'
import { getUserDetail, getUserSonglist, getUserSongLikeList } from '@/api/userdetail/userdetail.js'
import { ref, getCurrentInstance } from 'vue'
import { isPhone, isPwd, setItem, getItem } from '@/utils/utils.js'
import { useUserStore } from '@/store/user.js'
//接收父组件传递的自定义事件
const emit = defineEmits(['closeLogin'])

const instance = getCurrentInstance()
//仓库实例
const user = useUserStore()

//收集登录手机号
let phoneNum = ref('')
//收集登录密码
let password = ref('')
//登录的方式 | 注册
let loginWay = ref(0)
//是否获取到验证码
let isGetCaptcha = ref(false)
//获取验证码之后的文字提示
let tip = ref('')
//手机号验证码
let phoneCap = ref('')
//二维码登录的图片路径
let qrUrl = ref('')
//二维码失效显示文本
let failqr = ref(false)
//扫描二维码成功显示文本
let scanQr = ref(false)
//轮询二维码的定时器
let timer = ref('')

const validatePhone = (rule, value, callback) => {
    if (value === '')
        callback(new Error('请输入手机号'))
    else {
        if (!isPhone(value)) {
            callback(new Error('手机号格式不对'))
        }
        callback()
    }
}
const validatePwd = (rule, value, callback) => {
    if (value === '')
        callback(new Error('请输入密码'))
    else {
        if (value.length < 8) {
            callback(new Error('密码不能小于8位'))
        }
        if (!isPwd(value)) {
            callback(new Error('密码必须包含数字和字母'))
        }
        callback()
    }
}
const validateCheckPwd = (rule, value, callback) => {
    if (value === '')
        callback(new Error('请再次输入密码'))
    else {
        if (value !== ruleForm.value.pass)
            callback(new Error('两次输入密码不一致'))
        else
            callback()
    }
}

//定义的一些注册规则
let rules = ref({
    phone: [{ validator: validatePhone, trigger: 'blur', required: true }],
    pass: [{ validator: validatePwd, trigger: 'blur', required: true }],
    checkPass: [{ validator: validateCheckPwd, trigger: 'blur', required: true }],
    nickname: [{ message: '请输入昵称', trigger: 'blur', required: true }],
    captcha: [{ message: '请输入验证码', trigger: 'blur', required: true }],
})

//注册的用户信息收集
let ruleForm = ref({
    phone: '', //注册的手机号
    pass: '', //注册的密码
    checkPass: '', //验证密码
    nickname: '', //用户昵称
    captcha: '' //验证码
})

//关闭弹框事件
function closeLogin() {
    //触发父组件自定义事件
    emit('closeLogin')
}

//登录事件
async function phoneLogin(way) {
    //使用手机号和密码登录
    if (way === 1) {
        if (phoneNum.value.trim() === '' | password.value.trim() === '') {
            instance.appContext.config.globalProperties.$message({
                message: '手机号或密码不能为空',
                type: 'warning'
            })
            return;
        }
    } else {  //使用手机验证码登录
        if (phoneNum.value.trim() === '' || phoneCap.value.trim() === '') {
            instance.appContext.config.globalProperties.$message({
                message: '手机号或验证码不能为空',
                type: 'warning'
            })
            return;
        }
    }
    if (phoneCap.value.trim() !== '') {   //如果验证码存在|使用验证码登录   密码会失效
        let res = await loginByPhoneAndPwdOrCta(phoneNum.value, password.value, phoneCap.value)
        console.log(res);    //这里的登录接口好像有点问题，出现的是code=-460，网络拥堵 登录不了
    } else {  //使用密码登录
        let res1 = await loginByPhoneAndPwdOrCta(phoneNum.value, password.value)
    }
}

//修改登录方式
function changeLoginWay(way) {
    loginWay.value = way
    //如果不是扫码登录的话，就清除定时器
    if (way !== 1) {
        clearInterval(timer.value)
        if (way === 0)
            instance.refs.ruleForms.resetFields()  //重置注册表单
    }
    //扫码登录
    if (way === 1)
        qrLogin()  //调用函数

}

//获取验证码
async function getCaptcha() {
    //验证手机号是否为空
    if (phoneNum.value.trim() === '') {
        instance.appContext.config.globalProperties.$message({
            message: '手机号不能为空',
            type: 'warning',
            showClose: true
        })
        return
    }
    //向手机发送验证码
    let res = await sendCaptcha(phoneNum.value)
    switch (res.data.code) {
        case 200:  //发送成功
            instance.appContext.config.globalProperties.$message({
                showClose: true,
                message: "验证码已发送",
                type: "success",
            })
            isGetCaptcha.value = true  //确认获取到验证码
            let count = 60
            tip.value = `请${count}秒后再获取`
            let timeC = setInterval(() => {
                count--
                tip.value = `请${count}秒后再获取`
                if (count === 0) {
                    isGetCaptcha.value = false  //设为原始值
                    clearInterval(timeC)
                }
            }, 1000)
            break;
        case 400:
            instance.appContext.config.globalProperties.$message({
                showClose: true,
                message: "发送验证码超过限制:每个手机号一天只能发送5条验证码",
                type: "warning",
            })
            break;
        case 405:
            instance.appContext.config.globalProperties.$message({
                showClose: true,
                message: "发送验证码时间间隔过短",
                type: "warning",
            })
            break;
        default:
            instance.appContext.config.globalProperties.$message({
                showClose: true,
                message: "手机号不符合规范",
                type: "warning",
            })
            break;
    }
}


//扫二维码登录
async function qrLogin() {
    failqr.value = false
    scanQr.value = false
    //获取二维码key
    let res = await getQrKey()
    if (res.status === 200) {
        let key = res.data.data.unikey  //保存生成的key
        //生成二维码
        let res2 = await getLoginQr(key)
        if (res2.status === 200) {
            qrUrl.value = res2.data.data.qrimg  //保存二维码图片路径 base64格式
        }
        //利用定时器不断检查二维码状态
        timer.value = setInterval(async () => {
            let statusRes = await checkLoginQr(key)
            console.log(statusRes)
            if (statusRes.data.code === 800) {  //二维码过期
                instance.appContext.config.globalProperties.$message({
                    message: '二维码已失效',
                    type: 'error',
                    showClose: true
                })
                clearInterval(timer.value)  //清空定时器
                failqr.value = true  //显示二维码失效文本
            }
            if (statusRes.data.code === 802) {  //等待确认
                scanQr.value = true
            }
            if (statusRes.data.code === 803) {   //扫描成功
                //清除定时器
                clearInterval(timer.value)
                instance.appContext.config.globalProperties.$message({
                    message: '登录成功!',
                    type: 'success',
                    showClose: true
                })
                //登录成功之后 —— 存储cookie到localStorage中
                setItem('cookie', statusRes.data.cookie)

                //检查登录状态，并获取用户账号信息
                getUserLoginAccount()
            }
        }, 10000)
    }

}

//使用二维码登录 获取用户登录后的账户信息
async function getUserLoginAccount() {
    //检查登录状态
    let res = await loginStatus(getItem('cookie'))
    console.log(res.data.data.profile);
    if (res.data.data.profile) {  //这个对象存在即说明了处于登录状态
        loginSuccess(res.data)    //登录成功后的一些操作
    } else {
        instance.appContext.config.globalProperties.$message({
            message: '登录状态出现问题',
            type: 'warning',
            showClose: true
        })
    }
    // let res = await getUserAccount() //获取用户登录后账户信息
    // console.log('登录用户的信息', res);
    // if (res.status === 200) {
    //     let uid = res.data.account.id  //拿到用户id
    //     // let uid = 1745054804
    //     let res2 = await getUserDetail(uid)  //获取用户详细信息
    //     console.log(res2);
    //     if (res2.status === 200) {
    //         loginSuccess(res2)   //调用函数
    //     }
    // }
}

//登录成功后的一些操作
function loginSuccess(res) {
    //关闭登录框
    closeLogin()
    //更新登录状态
    user.isLogin = true
    //存储用户信息
    user.userInfo = res.data.profile
    //获取用户自己的歌单
    getUserSongListBy(res.data.profile.userId)
}

//获取用户自己新建的歌单和喜欢音乐的数据
async function getUserSongListBy(uid) {
    let res = await getUserSonglist(uid)  //获取用户私人歌单
    if (res.data.code === 200) {
        user.userSongList = res.data.playlist  //存到仓库中
    }
    let res1 = await getUserSongLikeList(uid, getItem('cookie'))  //获取用户喜欢音乐列表
    if (res1.data.code === 200) {
        user.likeSongIds = res1.data.ids   //存到仓库中
    }
}

//注册用户事件
function registerUser() {
    // console.log(instance.ctx.$refs.ruleForms);
    //如果验证通过
    instance.refs.ruleForms.validate(async (valid) => {
        if (valid) {
            //检查验证码
            let res = await checkCaptcha(ruleForm.phone.value, ruleForm.captcha.value)
            if (res.status === 200) {
                //提交服务器注册信息
                let res1 = await register(ruleForm.phone.value, ruleForm.captcha.value, ruleForm.password.value, ruleForm.nickname.value)
                if (res1.status === 200) {
                    instance.appContext.config.globalProperties.$message({
                        message: '注册成功!',
                        type: 'success',
                        showClose: true
                    })
                    setTimeout(() => {
                        changeLoginWay(0)
                    }, 500)
                } else {
                    instance.appContext.config.globalProperties.$message({
                        message: '该昵称已被占用!',
                        type: 'warning',
                        showClose: true
                    })
                }
            } else {
                instance.appContext.config.globalProperties.$message({
                    message: '验证码错误',
                    type: 'warning',
                    showClose: true
                })
            }
        } else {
            instance.appContext.config.globalProperties.$message({
                message: '请填写完整表单!',
                type: 'warning',
                showClose: true
            })
        }
    })
}

</script>

<style lang="scss" scoped>
.login-pop {
    position: absolute;
    top: 120px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 99;
    box-shadow: 0px 0px 5px 5px #eee;
    background: #dcdcdc;
    border-radius: 10px;
    width: 400px;
    height: 520px;
    background: #fff;
    text-align: center;

    .close {
        text-align: right;
        cursor: pointer;
        padding: 10px 10px 0 0;

    }

    .phone-login,
    .captcha-login {
        .imgs {
            margin-top: 30px;
        }

        .login-form {
            margin-top: 20px;
            padding-right: 30px;

            .ToCaptcha {
                cursor: pointer;
                position: absolute;
                right: 5px;
                font-size: 12px;
                color: var(--themeColor);
            }
        }
    }

    .other-way {
        margin-top: 20px;
        cursor: pointer;
    }

    .register {
        .reg-form {
            margin-top: 20px;
            padding-right: 30px;
        }

        .reg-btns {
            width: 250px;
            display: flex;
            justify-content: space-between;
            margin: 0 auto 12px;
            transform: translateX(18px);

            .reg-btn {
                width: 48%;
            }
        }
    }

    .captcha-input {
        position: relative;

        .captcha-btn {
            cursor: pointer;
            position: absolute;
            right: 5px;
            font-size: 12px;
            color: var(--themeColor);
        }

        .captcha {
            position: absolute;
            right: 5px;
            top: 0;
            font-size: 12px;
            color: #999;
        }
    }

    .qr-login {
        .qr {
            h2 {
                margin-top: 20px;
            }

            width: 100%;
            margin-bottom: 50px;

            img {
                width: 220px;
                height: 220px;
            }

            .failqr {
                margin-bottom: 5px;

                span {
                    color: var(--themeColor);
                    cursor: pointer;
                }

            }

            .text {
                margin-top: 10px;
            }

            .other-way {
                margin-top: 20px;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;

                .e {
                    font-size: 16px;
                    color: #515151;
                }

                span:hover {
                    color: var(--themeColor);
                }
            }
        }
    }
}



.icon-shouji {
    color: #d81e06;
    font-size: 100px;
}

:deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset !important;
}

:deep(.el-button) {
    width: 100%;
}

.icon-erweima {
    font-size: 14px;
}
</style>